package com.fxd.shopping.ware.service.impl;

import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.fxd.core.enums.PurchaseNeedStatusEnum;
import com.fxd.core.enums.PurchaseOrderStatusEnum;
import com.fxd.model.ware.PurchaseDetailEntity;
import com.fxd.shopping.ware.param.PurchaseFinishParam;
import com.fxd.shopping.ware.param.PurchaseItemParam;
import com.fxd.shopping.ware.param.PurchaseMergeParam;
import com.fxd.shopping.ware.service.PurchaseDetailService;
import com.fxd.shopping.ware.service.WareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxd.core.util.PageUtils;
import com.fxd.core.util.Query;

import com.fxd.shopping.ware.dao.PurchaseDao;
import com.fxd.model.ware.PurchaseEntity;
import com.fxd.shopping.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(PurchaseMergeParam param) {
        Long purchaseId = param.getPurchaseId();
        //新增采购单
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(PurchaseOrderStatusEnum.CREATED.getValue());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        List<Long> items = param.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntities = (List<PurchaseDetailEntity>) purchaseDetailService.listByIds(items);
        purchaseDetailEntities.forEach(purchaseDetailEntity -> {
            if (purchaseDetailEntity.getStatus() != PurchaseNeedStatusEnum.CREATED.getValue() && purchaseDetailEntity.getStatus() !=
                    PurchaseNeedStatusEnum.ASSIGEND.getValue()) {
                throw new ApiException("只能合并新建或者已分配的采购需求!");
            }
        });

        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(PurchaseNeedStatusEnum.ASSIGEND.getValue());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Override
    public void received(List<Long> ids) {
        //确定当前，采购单是新建或者已分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(item -> {
            return item.getStatus() == PurchaseOrderStatusEnum.CREATED.getValue() ||
                    item.getStatus() == PurchaseOrderStatusEnum.ASSIGEND.getValue();
        }).map(item -> {  //改变采购单的状态
            item.setStatus(PurchaseOrderStatusEnum.RECEIVE.getValue());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(collect);

        //改变采购需求的状态
        collect.forEach(item -> {
            List<PurchaseDetailEntity> list = purchaseDetailService.listDetailByPruchaseId(item.getId());
            List<PurchaseDetailEntity> collect1 = list.stream().map(i -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setStatus(PurchaseNeedStatusEnum.BUYING.getValue());
                purchaseDetailEntity.setId(i.getId());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect1);
        });

    }

    @Transactional
    @Override
    public void finish(PurchaseFinishParam param) {
        Boolean flag = true;
        List<PurchaseDetailEntity> list = new ArrayList<>();
        List<PurchaseItemParam> items = param.getItems();
        for (PurchaseItemParam item : items) {
            //如果采购项有一个失败，采购单状态为有异常
            if (item.getStatus() == PurchaseNeedStatusEnum.ERROR.getValue()) {
                flag = false;
            } else { //采购成功入库
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());

                wareSkuService.addStock(detailEntity.getSkuId(), detailEntity.getWareId(), detailEntity.getSkuNum());

            }
            //改变采购项的状态
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getItemId());
            purchaseDetailEntity.setStatus(item.getStatus());
            list.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(list);
        //改变采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(param.getId());
        purchaseEntity.setStatus(flag ? PurchaseOrderStatusEnum.FINISH.getValue() : PurchaseOrderStatusEnum.ERROR.getValue());
        this.updateById(purchaseEntity);

    }

}